package com.chat.simplechat.websocket;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.util.Iterator;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArraySet;

/**
 * @author wangyabin
 * @date 2022/10/26 15:17
 */
@Deprecated
@Slf4j
@Component
@ServerEndpoint("/websocket/{userId}")
public class WebSocket {
    
    private Session session;
    
    private String userId;

    /**静态变量，用来记录当前在线连接数。应该把它设计成线程安全的。*/
    private static int onlineCount = 0;

    /**
     * 记录
     */
    private static CopyOnWriteArraySet<WebSocket> webSockets = new CopyOnWriteArraySet<>();

    /**
     * 记录当前登录用户的会话
     */
    private static ConcurrentHashMap<String,Session> sessionPool = new ConcurrentHashMap<>();
    
    @OnOpen
    public void onOpen(Session session, @PathParam("userId") String userId){
        this.session = session;
        this.userId = userId;
        boolean exists = false;
        Iterator<WebSocket> iterator = webSockets.iterator();
        log.info("iterator:{}",iterator.hasNext());
        while (iterator.hasNext()){
            WebSocket webSocket = iterator.next();
            if(webSocket.userId.equals(userId)){
                exists = true;
                break;
            }
        }
        if(exists){
            //先删除之前的，在加入现在的
            this.remove();
        }
        webSockets.add(this);
        sessionPool.put(userId,session);
        log.info("【WebSocket】用户["+this.userId+"]已上线，当前在线用户数量:"+webSockets.size());
        this.addOnlineCount();
    }

    @OnClose
    public void onClose(){
        try {
            this.remove();
            log.info("【WebSocket】用户["+this.userId+"]已下线，当前在线用户数量:"+webSockets.size());
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    @OnMessage
    public void onMessage(String message){
        log.info("【WebSocket】收到客户端消息:"+message);
        if(StringUtils.hasText(message)){
            //解析发送的报文
            JSONObject jsonObject = JSON.parseObject(message);
            //追加发送人(防止串改)
            jsonObject.put("fromUserId",this.userId);
            String toUserId = jsonObject.getString("toUserId");
            Session session = sessionPool.get(toUserId);
            //传送给对应toUserId用户的websocket
            if(StringUtils.hasText(toUserId) && null != session){
                session.getAsyncRemote().sendText(jsonObject.toJSONString());
            }else{
                log.error("请求的userid:{}不在该服务器上",toUserId);
                //否则不在这个服务器上，发送到mysql或者redis
            }
        }
    }

    @OnError
    public void onError(Session session,Throwable throwable){
        log.error("消息发送错误，原因：{}",throwable.getMessage());
    }

    /**
     * 单点消息单用户发送
     * @param userId
     * @param message
     */
    public void sendOneMessage(String userId,String message){
        try {
            Session session = sessionPool.get(userId);
            if(null != session && session.isOpen()){
                session.getAsyncRemote().sendText(message);
                log.info("消息发送成功！");
            }
        } catch (Exception e) {
            throw new RuntimeException("消息发送失败:",e);
        }
    }

    /**
     * 单点消息多用户发送
     * @param userIds
     * @param message
     */
    public void sendMoreMessage(String[] userIds,String message){
        for (String userId : userIds) {
            try {
                Session session = sessionPool.get(userId);
                if(null != session && session.isOpen()){
                    session.getAsyncRemote().sendText(message);
                }
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }
    }

    /**
     * 广播轮询
     * @param message
     */
    public void radioBroadcast(String message){
        for (WebSocket webSocket : webSockets) {
            try {
                if(webSocket.session.isOpen()){
                    webSocket.session.getAsyncRemote().sendText(message);
                }
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }
    }

    /**
     * 消息发送
     * @param message
     */
    public void sendMessage(String message){
        this.session.getAsyncRemote().sendText(message);
    }

    /**
     * 移除用户
     */
    private void remove() {
        webSockets.remove(this);
        sessionPool.remove(userId);
        this.subOnlineCount();
    }

    public static synchronized int getOnlineCount(){
        return onlineCount;
    }

    public static synchronized void addOnlineCount(){
        WebSocket.onlineCount++;
    }

    public static synchronized void subOnlineCount(){
        WebSocket.onlineCount--;
    }
}
